<template>
  <el-dialog v-dialog-drag append-to-body :close-on-click-modal="false" width="1000px" :visible.sync="visible"
    :before-close="beforeClose" :title="title">
    <div class="wrapper">
      <el-divider direction="horizontal" content-position="left" v-if="operateType == 'split'">质量问题信息</el-divider>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="文件名称" prop="fileName">
              <el-input :disabled="operateType == 'view' || operateType == 'split'" v-model="form.fileName"
                placeholder="请输入编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文件分类" prop="fileItem">
              <el-select :disabled="operateType == 'view' || operateType == 'split'" v-model="form.fileItem"
                placeholder="请选择文件分类">
                <el-option v-for="dict in dict.type.list_quality_file_item_type" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发文单位" prop="fileCompanyName">
              <el-input :disabled="operateType == 'view' || operateType == 'split'" v-model="form.fileCompanyName"
                placeholder="请输入发文单位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发文单位类型" prop="fileType">
              <el-select :disabled="operateType == 'view' || operateType == 'split'" v-model="form.fileType"
                placeholder="请输入发文单位类型">
                <el-option v-for="dict in dict.type.list_quality_file_type" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="文件编码" prop="fileCode">
              <el-input disabled v-model="form.fileCode" placeholder="请输入文件编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上传日期" prop="fileUpTime">
              <el-date-picker disabled v-model="form.fileUpTime" type="date" placeholder="请选择问题附件上传日期"
                value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发文日期" prop="fileSubTime">
              <el-date-picker :disabled="operateType == 'view' || operateType == 'split'" v-model="form.fileSubTime"
                type="date" placeholder="请选择发文日期" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="要求整改完成日期" prop="fileRectificationTime">
              <el-date-picker :disabled="operateType == 'view' || operateType == 'split'"
                v-model="form.fileRectificationTime" type="date" placeholder="请选择要求整改完成日期" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="问题附件" prop="fileInfo">
          <FileUpload ref="fileUpload" :value="fileList" :viewMode="operateType == 'view' || operateType == 'split'">
          </FileUpload>
        </el-form-item>
      </el-form>
      <template v-if="operateType == 'split'">
        <div>
          <div v-for="(item, index) in splitList" :key="index">
            <el-divider direction="horizontal" content-position="left" v-if="operateType == 'split'">拆分信息</el-divider>
            <SplitForm ref="splitForm" :operateType="operateType" :form="item" :dicts="allDicts" />
            <div style="text-align: center;margin-bottom: 10px;">
              <el-button type="danger" size="mini" @click="deleteSplit(index)" v-if="item.canDel != '2'">删除</el-button>
            </div>
          </div>
          <div style="padding-left: 10px;">
            <el-button type="primary" size="mini" @click="addSplit">{{ splitList.length ? '再次拆分' : '拆分' }}</el-button>
          </div>
        </div>
      </template>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" size="mini" @click="submit" v-if="operateType != 'view'">确定</el-button>
      <el-button size="mini" @click="beforeClose">取消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import SplitForm from "../../qualityFileItem/components/splitForm.vue";
import { getDetail, addData, updateData, splitData,getDataList } from "../api";
import { getRevisePeople, getDutyArea } from "@/api/biz/ledger/ledger";
import { getTree } from "@/api/biz/enter/enterNext";
import { listType } from "@/api/list/type";
import { getQuestionList, getDataList as getSubList } from "../../qualityFileItem/api";
function required() {
  return { required: true, message: "此项不能为空", trigger: "change" }
}
function cloneObj(obj) {
  return JSON.parse(JSON.stringify(obj))
}
export default {
  name: "MainDialog",
  dicts: ["list_quality_overdue_status", "list_quality_file_type", "list_quality_file_item_type",
    "list_quality_data_source", "list_quality_data_status", "list_quality_rectification_deadline_status",
    "list_quality_question_beyond", "list_quality_question_analysis", "list_quality_level",
    "list_quality_rework_or_not", "list_quality_publish_or_not", "list_quality_file_type"],
  components: { SplitForm },
  props: {
    visible: Boolean,
    title: {
      type: String,
      default: "质量问题文件详情"
    },
    data: {
      type: Object,
      default: () => { }
    },
    operateType: {
      type: String,
      default: "view"
    }
  },
  data() {
    return {
      projectId: this.$store.state.app.selectData,
      fileList: [],
      form: {
        id: "",
        fileName: "",
        fileItem: "",
        fileCompanyName: "",
        fileType: "",
        fileUpTime: "",
        fileSubTime: "",
        fileRectificationTime: "",
        fileInfo: "",
      },
      rules: {
        fileName: [required()],
        fileItem: [required()],
        fileCompanyName: [required()],
        fileType: [required()],
        fileInfo: [required()],
        fileSubTime: [required()],
        fileRectificationTime: [required()],
      },
      splitForm: {
        id: "",
        fileId: "", // 质量问题ID
        workNo: "", // 问题编号
        splitTime: "", // 拆分时间
        questionDesc: "", // 问题描述
        supplement: "", // 补充说明
        dutyAreaId: null, // 责任区域
        dutyAreaName: "", // 责任区域
        controlMeasures: "", // 防治措施
        questionLevel: '', // 问题等级
        reworkOrNot: '', // 是否返工
        publishOrNot: '', // 是否公开
        rectificationDeadlineStatus: '', // 整改期限
        questionBeyond: '', // 问题类型
        questionAnalysis: '', // 问题分析
        questionId: null, // 质量问题分类
        questionIdName: '', // 质量问题分类
        reviseTheDates: '', // 整改截止时间
        dataSource: '', // 数据来源
        checkType: null, // 检查类型
        checkPeopleId: '', // 检查人
        revisePeopleId: '', // 整改人
        reviewUserNameId: '', // 复查人
        notifierId: '', // 通知人
        projectId: this.projectId,
        // canDel: "1", // 1可删除，2不可删除
      },
      splitList: [],
      dutyAreaOptions: [],
      checkTypeOptions: [],
      questionOptions: [],
      peopleOptions: [],
      libOptions:[]
    };
  },
  computed: {
    allDicts() {
      return {
        ...this.dict.type,
        libOptions: this.libOptions,
        dutyAreaOptions: this.dutyAreaOptions,
        questionOptions: this.questionOptions,
        peopleOptions: this.peopleOptions,
        checkTypeOptions: this.checkTypeOptions,
      }
    }
  },
  created() {
    this.initData();
  },
  methods: {
    //格式化数据
    // formatTreeData(data) {
    //   data.forEach((item) => {
    //     if (item.children && item.children.length) {
    //       this.formatTreeData(item.children)
    //     } else if (item.questionChildren && item.questionChildren.length) {
    //       item.questionChildren.forEach((subItem) => {
    //         subItem.label = subItem.dataSource;
    //       });
    //       item.children = item.questionChildren
    //     }
    //   });
    // },
    initData() {
      getRevisePeople({ projectId: this.projectId, hiddenTrouble: '0' }).then((data) => {
        const res = data.rows.map(item => ({ label: item.nickName, value: item.userId.toString() }))
        this.peopleOptions = res;
      });
      // 质量问题库
      getQuestionList().then((res) => {
          this.libOptions = res.data;
          // this.formatTreeData(this.libOptions);
        });
      // 责任区域
      getDutyArea({ projectId: this.projectId, hiddenTrouble: '0' }).then((response) => {
        this.dutyAreaOptions = response.data;
      });
      // 检查类型
      getTree({ checkTypeNo: null }).then((response) => {
        this.checkTypeOptions = response.data
      });
      // 质量问题分类
      listType().then((response) => {
        this.questionOptions = this.handleTree(response.data, "typeNo", "parentId");
      });
      if (this.operateType == 'add') {
        this.form.fileUpTime = this.parseTime(new Date(), '{y}-{m}-{d}');
        let num = '';
        for (var i = 0; i < 3; i++) {
          num += Math.floor(Math.random() * 10);
        }
        this.form.fileCode = "zlwtwj_" + this.parseTime(new Date(), '{y}{m}{d}{h}{i}{s}') + num;
      }
      if (this.operateType == 'view' || this.operateType == 'split') {
        Object.keys(this.rules).forEach(item => {
          delete this.rules[item]
        })
      }
      if (this.operateType == 'edit' || this.operateType == 'view' || this.operateType == 'split') {
        Object.keys(this.data).forEach(key => {
          this.$set(this.form, key, this.data[key])
        })
        if (this.form.fileInfo && this.form.fileInfo.length) {
          this.getFileList()
        }
      }
      if (this.operateType == 'split') {
        getSubList({ projectId: this.projectId, fileCode: this.form.fileCode }).then((data) => {
          this.splitList = data.rows
        });
      }
    },
    getFileList() {
      const ids = this.form.id
      getDetail(ids).then((response) => {
        this.fileList = response.data.fileDocAttachList.map((item) => {
          return Object.assign(item, {
            name: item.displayName + "." + item.extName,
            url: process.env.VUE_APP_MINIO_BASE_API + "/" + item.bucket + "/" + item.realName
          })
        });
      });
    },
    beforeClose() {
      this.$emit('update:visible', false);
    },
    syncFileList() {
      const fileUpload = this.$refs.fileUpload;
      const fileIds = fileUpload.getFileList().map(item => item.id)
      this.form.fileInfo = fileIds.join(",")
    },
    async submit() {
      if (this.operateType == 'split') {
        const forms = this.$refs.splitForm
        const ress = await Promise.all(forms.map(item => item.validate()))
        const hasFail = ress.some(item => item == false)
        if (hasFail) {
          return;
        }
        const splitRes = await splitData({
          fileId: this.data.id,
          data: this.splitList
        })
        if (splitRes.code == 200) {
          this.$emit("refresh")
          this.beforeClose()
        }
        return;
      }
      this.syncFileList();
      this.$refs.form.validate(async valid => {
        if (!valid) {
          // return this.$message.warning("表单校验未通过")
          return;
        }
        const fn = this.form.id ? updateData : addData;
        const res = await fn({ ...this.form, projectId: this.projectId })
        if (res.code == 200) {
          this.$emit("refresh")
          this.beforeClose()
        }
      })
    },
    addSplit() {
      const clone = cloneObj(this.splitForm)
      const splitTime = this.parseTime(new Date(), '{y}-{m}-{d}');
      let num = '';
      for (var i = 0; i < 3; i++) {
        num += Math.floor(Math.random() * 10);
      }
      const workNo = "zlwtk_" + this.parseTime(new Date(), '{y}{m}{d}{h}{i}{s}') + num;
      clone.splitTime = splitTime;
      clone.workNo = workNo;
      clone.fileId = this.form.id;
      clone.projectId = this.projectId;
      this.splitList.push(clone)
    },
    deleteSplit(index) {
      this.splitList.splice(index, 1)
    },
  },
};
</script>
<style lang="scss" scoped>
.wrapper {
  max-height: 500px;
  overflow-y: auto;
  overflow-x: hidden;

  .el-select {
    width: 100%;
  }

  .el-date-editor {
    width: 100%;
  }
}
</style>
